package com.yubest.junit.topdf;

import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormatRegistry;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.StreamOpenOfficeDocumentConverter;
import lombok.AllArgsConstructor;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

/**
 * @Author: hweiyu
 * @Date: 2023/3/30 16:29
 */
@AllArgsConstructor
public class LibreofficeToPdf implements ToPdf {

    private String host;

    private int port;

    @Override
    public byte[] to(byte[] bytes) {
        OpenOfficeConnection con = new SocketOpenOfficeConnection(this.host, this.port);
        try(ByteArrayOutputStream os = new ByteArrayOutputStream()) {
            con.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(con);
            DocumentFormatRegistry formatRegistry = new DefaultDocumentFormatRegistry();
            converter.convert(new ByteArrayInputStream(bytes), formatRegistry.getFormatByFileExtension("doc"), os,
                    formatRegistry.getFormatByFileExtension("pdf"));
            return os.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        } finally {
            con.disconnect();
        }
    }
}
